﻿#include "startserverstate.h"
#include <context/context.h>
#include "stopstate.h"
#include <pointer/basepointer.h>
#include <ipfivetuple.h>
#include <data/readyargs.h>
#include <data/startargs.h>
#include <QsLog.h>

StartServerState::StartServerState(Context *context, bool bServer)
    : BaseState(context, bServer)
{
}

StartServerState::~StartServerState()
{
    m_context->remove(this);
}

void StartServerState::process()
{
    QLOG_TRACE() << QObject::tr("StartServerState::process()");
    m_context->add(this);
}

void StartServerState::cancel()
{
    change(BaseState::Stop);
}

void StartServerState::onStateChanged(PointerCallback::State state, bool bCmd)
{
    if(bCmd && state != PointerCallback::Connected) // 指令链路断开的处理。
    {
        QLOG_TRACE() << QObject::tr("StartServerState client  disconnect！");
        cancel();
        return;
    }

    if(!bCmd && state == PointerCallback::Connected) // 数据链路连接的处理。
    {
        // 通知就绪。
        if(!m_context->ready())
        {
            QLOG_WARN() << QObject::tr("Ready command send failed, change state to stop.");
            cancel();
            return;
        }
        QLOG_TRACE() << QObject::tr("Change to WorkReply State");
        change(BaseState::WorkReply);
    }
}

void StartServerState::onStart(const StartArgs &args)
{
    // 收到start的指令后，需要根据指令的内容建立与客户端之间的数据链路
    // 当数据链路成功连接后，进入下一个状态（WorkReply)
    IPFiveTuple tuple = args.ipTuple();
    //   context 代理创建数据链路。
    bool buildRet = m_context->buildDataLink(tuple);

    QString msg = QString(QObject::tr("Receive start args %1, build data link %2!")).arg(tuple.toString())
            .arg(buildRet ? "sucess" : "failed.");
    QLOG_INFO() << msg;
}

void StartServerState::onStop(const StopArgs &args)
{
    Q_UNUSED(args)
}

void StartServerState::onRequest(const RequestPacket &pack)
{
    Q_UNUSED(pack)
}

void StartServerState::onReply(const ReplyPacket &pack)
{
    Q_UNUSED(pack)
}

void StartServerState::onReady(const ReadyArgs &args)
{
    Q_UNUSED(args)
}
